<?php

namespace App\Listeners\Subscriber;

use App\Models\Project;
use App\Models\Station\Summary;
use Illuminate\Events\Dispatcher;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\Station\Report\CreatedEvent;

class StationReportEventSubscriber implements ShouldQueue
{
	/**
	 * 当创建报岗记录时触发该方法
	 *
	 * Date: 02/05/2018
	 * @author George
	 * @param CreatedEvent $event
	 * @throws \Throwable
	 */
	public function onCreated(CreatedEvent $event)
	{
		$report = $event->report;

		$summary = Summary::query()->where('project_id', $report->project_id)->where('date', date('Y-m-d'))->first();

		if ($summary) {
			// 更新完成数量
			$summary->actual_quantity += 1;
			// 更新未完成数量
			$summary->unreport_count = $summary->timings_count - $summary->actual_quantity;
			// 更新完成率
			$summary->finish_rate = ($summary->actual_quantity / $summary->timings_count) * 100;
			$summary->save();
		} else {
			/**
			 * 获取项目信息
			 */
			$project = Project::withCount('timings')->where('id', $report->project_id)->first();

			$attributes = [
				'company_id' => $report->company_id,
				'project_id' => $report->project_id,
				'project_name' => $project->name,
				// 应报岗数
				'timings_count' => $project->timings_count,
				// 实际完成数
				'actual_quantity' => 1,
				// 未完成数
				'unreport_count' => $project->timings_count - 1,
				// 完成率
				'finish_rate' => (1 / $project->timings_count) * 100,
				'date' => date('Y-m-d')
			];

			Summary::create($attributes);
		}
	}

	/**
	 * 为订阅者注册监听器
	 *
	 * Date: 23/03/2018
	 * @author George
	 * @param Dispatcher $events
	 */
	public function subscribe(Dispatcher $events)
	{
		$events->listen(
			'App\Events\Station\Report\CreatedEvent',
			'App\Listeners\Subscriber\StationReportEventSubscriber@onCreated'
		);
	}
}
